package com.cskaoyan.market.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@RestController
@RequestMapping("wx/storage/fetch/")
public class WxStorageFetchController {
    @GetMapping("{file}")
    public void read(@PathVariable("file") String key, HttpServletRequest req, HttpServletResponse resp) throws IOException {

        File file = new File("D:/software_development/javaproj/image/" + key);
        if(file.exists() && file.isFile()){
            //响应给客户端:服务器给客户端返回信息 响应报文 响应体  哪个方法设置响应体呢？ 字符还是字节
            ServletOutputStream outputStream = resp.getOutputStream();
            FileInputStream fileInputStream = new FileInputStream(file);
            int length = 0;
            byte[] bytes = new byte[1024];
            while ((length = fileInputStream.read(bytes)) != -1){
                outputStream.write(bytes, 0, length);
            }
            return;
        }
        resp.setStatus(404);
        //404
    }
}
